package com.imcrl.core.state
{
	import com.imcrl.event.StateEvent;
	
	import starling.display.DisplayObjectContainer;
	
	
	public class SceneMachine extends StateMachine
	{
		private var container:DisplayObjectContainer;
		public function SceneMachine(container:DisplayObjectContainer)
		{
			this.container=container;
		}
		
		
		override public function set state(name:String):void{
			var scene:Scene=states[name];
			if(currentState==scene)return;
			
			if(currentState){
				currentState.end();
			}
	
			currentState=scene;
			
			if(scene){
				container.addChild(scene);
				if(scene.initialized==false)scene.initialize();
				scene.addEventListener(StateEvent.END,stateEventHandle);
				scene.addEventListener(StateEvent.START,stateEventHandle);
				scene.start();
			}
			
		}
		
		private function stateEventHandle(event:StateEvent):void{
			var scene:Scene=event.target as Scene;
			
			switch(event.type){
				case StateEvent.END :
					scene.removeEventListener(StateEvent.START,stateEventHandle);
					scene.removeEventListener(StateEvent.END,stateEventHandle);
					endEffect(scene);
					
					var nextScene:String=scene.nextScene;
					if(nextScene){
						if(scene==currentState){
							currentState=null;
						}
						this.state=nextScene;
					}
					break;	
				
				case StateEvent.START :
					scene.removeEventListener(StateEvent.START,stateEventHandle);
					startEffect(scene);
					break;
			}
		}
		
		
		/**
		 * 统一结束效果(结束效果完成后,必须从容器中删除掉场景); 
		 * @param state
		 * 
		 */		
		protected function endEffect(state:Scene):void{
			container.removeChild(state);
		}
		
		
		/**
		 * 统一开始效果; 
		 * @param state
		 * 
		 */		
		protected function startEffect(state:Scene):void{
			//todo alpha显示效果;(iphone是由场景自己做)
		}
		
	}
}